class H5ApiServer {
    static postParams = {};
    constructor(type = "get", postParamsTimeout = 2000) {
        this.type = type;
        this.postParamsTimeout = postParamsTimeout;
    }
    listen(callback) {
        function urlParamToJson(url) {
            if (!url) {
                return {};
            }

            let json = {};
            url.substring(url.indexOf('?') + 1)
                .trim()
                .split('&')
                .forEach(item => json[item.split('=')[0]] = item.split('=')[1]);

            return json;
        }
        function cookieToJson(cookieString) {
            // 分割 cookie 字符串为键值对数组
            var cookieArr = cookieString.split(';');

            // 初始化空对象用于存储解析后的键值对
            var cookieJson = {};

            // 遍历键值对数组，将每一对分割为键和值，并存储到 cookieJson 对象中
            cookieArr.forEach(function (cookie) {
                var parts = cookie.split('=');
                var key = parts[0].trim();
                var value = parts.length > 1 ? decodeURIComponent(parts[1].trim()) : '';
                cookieJson[key] = value;
            });

            return cookieJson;
        }
        if (this.type == "get") {
            callback(urlParamToJson(window.location.href));
        } else if (this.type == "post") {
            if (document.cookie != "") {
                callback(cookieToJson(document.cookie));
            } else {
                sleep(this.postParamsTimeout).then(() => {
                    callback(H5ApiServer.postParams);
                });
            }
        } else {
            throw `Unknown request type "${this.type}"!`;
        }
    }
    echo(message) {
        document.open();
        document.write("H5ApiServerResult=" + message);
    }
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}
window.addEventListener('message', e => {
    H5ApiServer.postParams = JSON.parse(e.data);
}, false);
